package libretto.activity;

import java.util.HashMap;
import java.util.Map;

import libretto.connection.ConnectionManager;
import libretto.connection.SsolHttpClient;
import libretto.utils.Utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

public class IscrizioneAppello extends Activity implements OnClickListener {

	private static final String TAG = IscrizioneAppello.class.getName();
	private static final int SUCCESS = 0;
	private static final int FAIL = 1;

	private ConnectionManager cm;
	private Map<String, String> params;
	private String url;
	private String page_URL;

	private TextView corso;
	private TextView esame;
	private TextView data;
	private TextView luogo;
	private TextView verba;
	private TextView iscritti;
	private TextView num;
	private Spinner tipo;
	private ToggleButton ok;
	private LinearLayout ly_ordine;
	private ArrayAdapter<String> adapter;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.iscrizione_3);
		init();
		Intent intent = getIntent();
		String pkg = getPackageName();
		String page_HTML = intent.getStringExtra(pkg + ".iscriz");
		page_URL = intent.getStringExtra(pkg + ".url");
		retriveData(page_HTML);
	}

	private void init() {
		cm = ConnectionManager.getInstance();

		corso = (TextView) findViewById(R.id.tv_iscr_corso);
		esame = (TextView) findViewById(R.id.tv_iscr_esame);
		data = (TextView) findViewById(R.id.tv_iscr_data);
		luogo = (TextView) findViewById(R.id.tv_iscr_luogo);
		verba = (TextView) findViewById(R.id.tv_iscr_verb);
		iscritti = (TextView) findViewById(R.id.tv_iscr_iscritti);
		num = (TextView) findViewById(R.id.tv_iscr_num);
		tipo = (Spinner) findViewById(R.id.sp_iscr);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);
		ok = (ToggleButton) findViewById(R.id.tb_iscr_ok);
		ok.setOnClickListener(this);
		ly_ordine = (LinearLayout) findViewById(R.id.ly_iscr_num);
		params = new HashMap<String, String>();
	}

	private void retriveData(String page_HTML) {
		if (page_HTML == null) {
			return;
		}

		Document jsoupDoc = Jsoup.parse(page_HTML);
		Element fieldset = jsoupDoc.select("fieldset").first();

		String s[] = fieldset.select("legend").text().split(" - ");
		corso.setText(s[0]);
		esame.setText(s[1]);

		Element form = fieldset.select("form").first();
		url = form.attr("action");
		Elements inputs = form.select("input");
		for (Element input : inputs) {
			params.put(input.attr("name"), input.attr("value"));
		}

		Elements trs = jsoupDoc.select("fieldset>form>table").select("tr");
		String action = params.get("azione");

		if (action.equals("INSERT")) {

			adapter.clear();
			Elements options = fieldset.select("select>option");
			for (Element option : options) {
				adapter.add(option.text());
			}
			tipo.setAdapter(adapter);
			tipo.setEnabled(true);

			Elements tds = trs.get(0).select("td.Content_Chiaro");
			data.setText(tds.get(0).text());
			iscritti.setText(tds.get(1).text());

			tds = trs.get(2).select("td.Content_Chiaro");
			luogo.setText(tds.text());

			tds = trs.get(3).select("td.Content_Chiaro");
			verba.setText(tds.text());

			ok.setChecked(false);
			ly_ordine.setVisibility(View.INVISIBLE);
		}
		if (action.equals("DELETE")) {

			Elements tds = trs.get(0).select("td.Content_Chiaro");
			num.setText(tds.get(0).text());
			iscritti.setText(tds.get(1).text());

			tds = trs.get(1).select("td.Content_Chiaro");
			data.setText(tds.text());

			tds = trs.get(2).select("td.Content_Chiaro");
			adapter.clear();
			adapter.add(tds.text());
			tipo.setAdapter(adapter);
			tipo.setEnabled(false);

			tds = trs.get(3).select("td.Content_Chiaro");
			luogo.setText(tds.text());

			tds = trs.get(4).select("td.Content_Chiaro");
			verba.setText(tds.text());

			ok.setChecked(true);
			ly_ordine.setVisibility(View.VISIBLE);

		}
	}

	private Handler appelloHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case SUCCESS:
				try {
					retriveData(Utils.inputStreamToString(cm
							.getSsolConnection().getEntity().getContent()));
				} catch (Exception e) {
					Log.e(TAG, e.getMessage());
				}
				progressDialog.dismiss();
				break;
			case FAIL:
				progressDialog.dismiss();
				break;
			default:
				break;
			}
		}
	};

	private void iscrizione(String link) {
		if (Utils.isLink(link)) {
			params.put("tipo_iscrizione", tipo.getSelectedItem().toString());
			cm.getSsolConnection().post(link, params);
			cm.getSsolConnection().consumeContent();
			cm.getSsolConnection().get(page_URL);
			appelloHandler.sendEmptyMessage(SUCCESS);
		} else {
			appelloHandler.sendEmptyMessage(FAIL);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == ok) {
			progressDialog = ProgressDialog.show(IscrizioneAppello.this,
					"Please wait...", "Loading data ...", true);
			new Thread(new Runnable() {
				@Override
				public void run() {
					iscrizione(SsolHttpClient.AUTH_URI + url);
				}
			}).start();
		}
	}
}
